<?php
require_once 'db.php';

// 获取所有文章
function getArticles() {
    global $pdo;
    $stmt = $pdo->query("SELECT posts.*, users.username AS author, users.display_name
                         FROM posts
                         JOIN users ON posts.user_id = users.user_id
                         WHERE posts.status = 'published'
                         ORDER BY posts.created_at DESC");
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// 根据ID获取文章
function getArticleById($id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT posts.*, users.username AS author, users.display_name
                           FROM posts
                           JOIN users ON posts.user_id = users.user_id
                           WHERE posts.post_id = ?");
    $stmt->execute([$id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// 获取用户文章
function getUserArticles($user_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM posts WHERE user_id = ? ORDER BY created_at DESC");
    $stmt->execute([$user_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// 创建新文章
function createArticle($user_id, $title, $content, $status = 'published', $category_ids = []) {
    global $pdo;
    try {
        $pdo->beginTransaction();
        
        $stmt = $pdo->prepare("INSERT INTO posts (user_id, title, content, status) VALUES (?, ?, ?, ?)");
        $stmt->execute([$user_id, $title, $content, $status]);
        
        $post_id = $pdo->lastInsertId();
        
        // 设置分类
        if (!empty($category_ids)) {
            setArticleCategories($post_id, $category_ids);
        }
        
        $pdo->commit();
        return $post_id;
    } catch (Exception $e) {
        $pdo->rollBack();
        return false;
    }
}

// 更新文章
function updateArticle($post_id, $title, $content, $status = 'published', $category_ids = []) {
    global $pdo;
    try {
        $pdo->beginTransaction();
        
        $stmt = $pdo->prepare("UPDATE posts SET title = ?, content = ?, status = ?, updated_at = CURRENT_TIMESTAMP WHERE post_id = ?");
        $stmt->execute([$title, $content, $status, $post_id]);
        
        // 更新分类
        setArticleCategories($post_id, $category_ids);
        
        $pdo->commit();
        return true;
    } catch (Exception $e) {
        $pdo->rollBack();
        return false;
    }
}

// 删除文章
function deleteArticle($post_id) {
    global $pdo;
    $stmt = $pdo->prepare("DELETE FROM posts WHERE post_id = ?");
    return $stmt->execute([$post_id]);
}

// 增加文章浏览量
function incrementViewCount($post_id) {
    global $pdo;
    $stmt = $pdo->prepare("UPDATE posts SET view_count = view_count + 1 WHERE post_id = ?");
    return $stmt->execute([$post_id]);
}

// 获取分类名称
function getCategoryName($category) {
    $categories = [
        'technology' => '技术',
        'design' => '设计',
        'life' => '生活',
        'travel' => '旅行',
        'reading' => '阅读'
    ];
    return $categories[$category] ?? $category;
}

// 用户登录认证
function authenticate($username, $password) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
    $stmt->execute([$username, $password]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($user) {
        return $user;
    }
    return false;
}

// 获取用户信息
function getUserById($user_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM users WHERE user_id = ?");
    $stmt->execute([$user_id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// 更新用户信息
function updateUserProfile($user_id, $display_name, $email, $bio) {
    global $pdo;
    $stmt = $pdo->prepare("UPDATE users SET display_name = ?, email = ?, bio = ? WHERE user_id = ?");
    return $stmt->execute([$display_name, $email, $bio, $user_id]);
}

// 更新用户密码
function updateUserPassword($user_id, $new_password) {
    global $pdo;
    $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE user_id = ?");
    return $stmt->execute([$new_password, $user_id]);
}

// 验证用户密码
function verifyUserPassword($user_id, $password) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT password FROM users WHERE user_id = ? AND password = ?");
    $stmt->execute([$user_id, $password]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($user) {
        return true;
    }
    return false;
}

// 检查文章是否属于用户
function isArticleOwner($post_id, $user_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM posts WHERE post_id = ? AND user_id = ?");
    $stmt->execute([$post_id, $user_id]);
    return $stmt->fetchColumn() > 0;
}

// 获取文章统计信息
function getArticleStats($user_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT 
                            COUNT(*) as total_posts,
                            SUM(view_count) as total_views,
                            COUNT(CASE WHEN status = 'published' THEN 1 END) as published_posts
                           FROM posts WHERE user_id = ?");
    $stmt->execute([$user_id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// 获取所有分类
function getAllCategories() {
    global $pdo;
    $stmt = $pdo->query("SELECT * FROM categories ORDER BY name");
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// 根据ID获取分类
function getCategoryById($category_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM categories WHERE category_id = ?");
    $stmt->execute([$category_id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// 创建分类
function createCategory($name, $description = '') {
    global $pdo;
    $stmt = $pdo->prepare("INSERT INTO categories (name, description) VALUES (?, ?)");
    return $stmt->execute([$name, $description]);
}

// 更新分类
function updateCategory($category_id, $name, $description = '') {
    global $pdo;
    $stmt = $pdo->prepare("UPDATE categories SET name = ?, description = ? WHERE category_id = ?");
    return $stmt->execute([$name, $description, $category_id]);
}

// 删除分类
function deleteCategory($category_id) {
    global $pdo;
    // 首先删除文章分类关联
    $stmt = $pdo->prepare("DELETE FROM post_categories WHERE category_id = ?");
    $stmt->execute([$category_id]);
    
    // 然后删除分类
    $stmt = $pdo->prepare("DELETE FROM categories WHERE category_id = ?");
    return $stmt->execute([$category_id]);
}

// 获取文章的分类
function getArticleCategories($post_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT c.* FROM categories c
                          JOIN post_categories pc ON c.category_id = pc.category_id
                          WHERE pc.post_id = ?");
    $stmt->execute([$post_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// 获取文章的分类ID列表
function getArticleCategoryIds($post_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT category_id FROM post_categories WHERE post_id = ? LIMIT 1");
    $stmt->execute([$post_id]);
    $category_id = $stmt->fetchColumn();
    
    if ($category_id) {
        return [['category_id' => $category_id]];
    }
    return [];
}

// 设置文章分类
function setArticleCategories($post_id, $category_ids) {
    global $pdo;
    // 先删除现有的分类关联
    $stmt = $pdo->prepare("DELETE FROM post_categories WHERE post_id = ?");
    $stmt->execute([$post_id]);
    
    // 添加新的分类关联
    if (!empty($category_ids)) {
        $stmt = $pdo->prepare("INSERT INTO post_categories (post_id, category_id) VALUES (?, ?)");
        foreach ($category_ids as $category_id) {
            $stmt->execute([$post_id, $category_id]);
        }
    }
    return true;
}

// 获取带分类信息的文章
function getArticlesWithCategories() {
    global $pdo;
    $stmt = $pdo->query("SELECT posts.*, users.username AS author, users.display_name,
                         c.category_id as category_ids,
                         c.name as category_names
                         FROM posts
                         JOIN users ON posts.user_id = users.user_id
                         LEFT JOIN post_categories pc ON posts.post_id = pc.post_id
                         LEFT JOIN categories c ON pc.category_id = c.category_id
                         WHERE posts.status = 'published'
                         ORDER BY posts.created_at DESC");
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// 根据分类获取文章
function getArticlesByCategory($category_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT posts.*, users.username AS author, users.display_name
                          FROM posts
                          JOIN users ON posts.user_id = users.user_id
                          JOIN post_categories pc ON posts.post_id = pc.post_id
                          WHERE pc.category_id = ? AND posts.status = 'published'
                          ORDER BY posts.created_at DESC");
    $stmt->execute([$category_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// 安全截断中文字符串，避免乱码
function mb_substr_safe($string, $start, $length, $encoding = 'UTF-8') {
    // 移除HTML标签
    $plain_text = strip_tags($string);
    
    // 使用mb_substr安全截断
    $truncated = mb_substr($plain_text, $start, $length, $encoding);
    
    // 如果截断后的长度小于原长度，添加省略号
    if (mb_strlen($plain_text, $encoding) > $length) {
        $truncated .= '...';
    }
    
    return $truncated;
}
?>